﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MySql.Data.MySqlClient;
using System.Collections;

namespace aspDBTest
{
	public partial class SiteMaster : System.Web.UI.MasterPage
	{
		//TODO create session vars
		protected void Page_Load(object sender, EventArgs e)
		{

		}
		protected void runQuery(object sender, EventArgs e)
		{
		/*
		 * 
		 * TODO: lots, this obviously won't compile, I'm just committing/pushing to add the tests folder to the git repo
		 * 
		 */
			MySqlConnection conn = new MySqlConnection("Server=" + dbhost.Text + ";Username=" + dbuser.Text + ";Password=" + dbpass.Text);
			MySqlCommand cmd = new MySqlCommand("", conn);

			if (dbquery.Text == "")
			{
				return;
			}
			try
			{
				conn.Open();
			}
			catch (Exception x)
			{
				//TODO: unrollException(x);
				dbresult.InnerText = "Exception on open()";
				return;
			}
			cmd.CommandText = dbquery.Text;

			try
			{
				MySqlDataReader data = cmd.ExecuteReader();

				dbresult.InnerText = "";	// clear old result
				// print column names
				for (int i = 0; i < data.FieldCount; i++)
				{
					//Console.Write((i > 0 ? " | " : "\t") + "[" + data.GetName(i).ToString() + "]");
					temp = data.GetName(i).ToString();
					((string[]) resTable[resTable.Count-1])[i] = temp;
					fieldSizes[i] = temp.Length;
				}
				//Console.WriteLine();
				// print rows
				while(data.Read())
				{
					resTable.Add(new string[data.FieldCount]);
					for (int i = 0; i < data.FieldCount; i++)
					{
						//Console.Write((i > 0 ? " | " : "\t") + data.GetValue(i).ToString());
						temp = data.GetValue(i).ToString();
						((string[]) resTable[resTable.Count-1])[i] = temp;
						// update
						if (temp.Length > fieldSizes[i])
						{
							fieldSizes[i] = temp.Length;
						}
					}
					//Console.WriteLine();
				}
				data.Close();
			}
			catch(MySqlException x)
			{
				unrollException(x);
			}
			finally
			{
				conn.Close();
			}

			/***
			 * 
			 * php for tabular petty print
			 * 
			 ***/
			if (!$queryStr || $queryStr=="")		//check for no query
				exit("\n\t</body>\n</html>");

			if(!$conn = @mysqli_connect($_SESSION['myHost'],$_SESSION['myUser'],$_SESSION['myPass']))	//connect
				exit(mysqli_connect_error()."\n\t\t<script>document.query.queryStr.value=\""
					.str_replace("\r\n","\\n",addslashes($queryStr))."\";</script>\n\t</body>\n</html>");

			$queryArr = explode(";",$queryStr);		//seperate queries

			for($i = 0; $i < count($queryArr); $i++)	//for each query
			{
				$queryArr[$i] = trim($queryArr[$i]);		//remove whitespace

				if ($queryArr[$i] == "")			//skip empty queries
					continue;

				echo "<br />\n\t\t<big><span style=\"color:#80b046;\""
					." onclick=\"queryStr.value += this.innerHTML + ';\\n';\">"	//print query
					.$queryArr[$i]."</span></big>\n\t\t<br /><br />\n\t\t";

				if (($res = $conn->query($queryArr[$i])) === FALSE)	//run & validate query (false = bad query)
					exit(($conn->error)."\n\t\t<script>document.query.queryStr.value=\""
						.str_replace("\r\n","\\n",addslashes($queryStr))."\";</script>\n\t</body>\n</html>");

				if ($res === TRUE || !$row = $res->fetch_assoc())	//validate result (true = good query w/ no result)
				{							//and get first row (empty row = empty result)
					echo "No Result\n\t\t<br /><br />";
					continue;
				}

				echo "\n\t\t<table border=\"1\">\n\t\t\t<thead>\n\t\t\t\t<tr>";	//start table
				$columns = array_keys($row);					//get column names (keys of assoc array)
				foreach ($columns as $colName)					//print column names
					echo "<th><font color=\"#0088ff\">$colName</font></th>";
				echo "</tr>\n\t\t\t</thead>\n\t\t\t<tbody>";

				do								//print rows
				{
					echo "\n\t\t\t\t<tr>";
					foreach ($row as $col)	//print each column of row
						echo "<td>$col</td>";
					echo "</tr>";
				}
				while ($row = $res->fetch_row());

				echo "\n\t\t\t</tbody>\n\t\t</table>\n\t\t<br />";		//end table

				$res->close();
			}
			$conn->close();
		}
	}
}
